package com.ngmaster.socket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Tcp服务器消息处理
 *
 */
public class TcpHandler extends SimpleChannelInboundHandler<Object> {

	/**
	 * Tcp逻辑
	 */
	private ITcpLogic logic = null;
	
	/**
	 * Tcp服务器处理
	 * @param logic
	 */
	public TcpHandler(ITcpLogic logic) {
		this.logic = logic;
	}

	/**
	 * 有消息过来
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object arg1) throws Exception {
		ByteBuf buf = (ByteBuf)arg1;
		logic.Receive(ctx, buf);
	}
	
	/**
	 * 发送到客户端
	 */
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	/**
	 * 异常了
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
	
	/**
	 * 建立连接
	 */
	@Override  
    public void channelActive(ChannelHandlerContext ctx) {
		logic.Active(ctx);
    } 
	
	/**
	 * 失去连接
	 */
	@Override  
    public void channelInactive(ChannelHandlerContext ctx){
		logic.Inactive(ctx);
    } 
}
